<script setup lang="ts">
import useDialog from "@/hooks/useDialog.ts";
import SysDialog from "@/components/dialog/SysDialog.vue";
import SelectChecked from "@/components/selectChecked/SelectedChecked.vue";
import {ElMessage, FormInstance} from "element-plus";
import {nextTick, onMounted, reactive, ref} from "vue";
import {getParentApi, addApi, getListApi,editApi,deleteApi} from "@/api/menu/index.ts";
import {User} from "@/api/user/type.ts";
import {SysMenu} from "@/api/menu/type.ts";
// 弹框属性
const {dialog, onShow, onClose, onConfirm} = useDialog()
import useInstance from "@/hooks/useInstance.ts";
import ElIconPicker from "@/components/iconPicker/ElIconPicker.vue";
// 获取全局 global
const {global} = useInstance()

// 表单ref属性
const addRef = ref<FormInstance>()
// 新增表单绑定对象
const addModel = reactive({
  id: undefined,
  parentId: undefined,
  title: '',
  code: '',
  name: '',
  path: '',
  url: '',
  type: '',
  icon: '',
  parentName: '',
  orderNum: undefined,
})


// 表单校验规则
const rules = reactive({
  parentId: [
    {required: true, message: '请选择上级菜单', trigger: 'change'},
  ],
  title: [
    {required: true, message: '请输入菜单名称', trigger: 'blur'},
  ],
  code: [
    {required: true, message: '请输入菜单编码', trigger: 'blur'},
  ],
  name: [
    {required: true, message: '请输入路由名称', trigger: 'blur'},
  ],
  path: [
    {required: true, message: '请输入路由path', trigger: 'blur'},
  ],
  type: [
    {required: true, message: '请选择菜单类型', trigger: 'change'},
  ],
  icon: [
    {required: true, message: '请输入菜单图标', trigger: 'blur'},
  ],
  orderNum: [
    {required: true, message: '请输入排序号', trigger: 'blur'},
  ],
  url: [
    {required: true, message: '请输入组件路径', trigger: 'blur'},
  ]
})

// 上级菜单数据
const treeList = ref([])
const getParent = async () => {
  try {
    const result = await getParentApi();
    treeList.value = result.data
  } catch (error) {
    console.log(error)
  }
}
// 上级下单选中事件
const treeClick = (item: any) => {
  addModel.parentName = item.title
}

// 表格数据
const tableData = ref([])
// 新增按钮
const addBtn = () => {
  dialog.title = '新增菜单'
  dialog.height = 270
  // 显示弹框
  onShow()
  // 获取上级菜单
  getParent()
  // 清理表单
  addRef.value?.resetFields()
  // 清空值
  Object.assign(addModel, {
    id: undefined,
    parentId: undefined,
    title: '',
    code: '',
    name: '',
    path: '',
    url: '',
    type: '',
    icon: '',
    parentName: '',
    orderNum: '',
  })
}

// 表单提交
const commit = () => {
  addRef.value?.validate(async (valid) => {
    if (valid) {
      console.log('通过')
      try {
        console.log(addModel)
        // 提交请求
        if (!addModel.id) {
          const result = await addApi(addModel);
          ElMessage.success('新增菜单成功')
        } else {
          const result = await editApi(addModel);
          ElMessage.success('修改菜单成功')
        }
        // 刷新列表
        getList()
        //关闭弹框
        onClose()
      } catch (error) {
      }
    }
  })
}

// 获取表格数据
const getList = async () => {
  try {
    const result = await getListApi();
    tableData.value = result.data
  } catch (error) {
    console.log(error)
  }
}


// 编辑按钮
const editBtn = async (row: SysMenu) => {
  console.log(row)
  // 显示弹框
  dialog.title = '编辑菜单'
  dialog.height = 270
  // 显示弹框
  onShow()
  // 清理表单
  addRef.value?.resetFields()
  // 获取上级菜单
  getParent()
  // 回显数据
  Object.assign(addModel, row)
}
// 删除按钮
const deleteBtn = async (id: number) => {
  const confirm = await global.$myConfirm('此操作将永久删除该菜单，是否继续?');
  if (confirm) {
    try {
      const result = await deleteApi(id)
      ElMessage.success('删除成功')
      // 刷新列表
      getList()
    } catch (error) {
      console.log(error)
    }
  }
}

// 表格高度
const tableHeight = ref()

onMounted(() => {
  getList()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 200
  })
})


</script>

<template>
  <el-main>
    <el-button icon="Plus" type="primary" @click="addBtn" v-permission="['sys:menu:add']">新增</el-button>
    <!--表格-->
    <el-table :height="tableHeight" :data="tableData" border stripe row-key="id" default-expand-all style="margin-top: 20px">
      <el-table-column prop="title" label="菜单名称" width="140" />
      <el-table-column prop="icon" label="菜单图标" width="100">
        <template #default="scope">
          <el-icon v-if="scope.row.icon">
            <component :is="scope.row.icon" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.type == 0" type="primary" effect="dark">目录</el-tag>
          <el-tag v-if="scope.row.type == 1" type="success" effect="dark">菜单</el-tag>
          <el-tag v-if="scope.row.type == 2" type="warning" effect="dark">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="parentName" label="上级菜单" width="100"/>
      <el-table-column prop="name" label="路由名称" width="160"/>
      <el-table-column prop="path" label="路由地址"  width="160"/>
      <el-table-column prop="code" label="权限字段" width="180"/>
      <el-table-column prop="url" label="组件路径" width="190"/>
      <el-table-column prop="orderNum" label="序号"  width="80"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button icon="edit" link  size="small" type="primary" @click.prevent="editBtn(scope.row)" v-permission="['sys:menu:update']">编辑</el-button>
          <el-button icon="delete" link  size="small" type="danger" @click.prevent="deleteBtn(scope.row.id)" v-permission="['sys:menu:delete']">删除</el-button>
        </template>
      </el-table-column>

    </el-table>


    <!--新增、编辑-->
    <SysDialog
        :title="dialog.title"
        :width="dialog.width"
        :height="dialog.height"
        :visible="dialog.visible"
        @on-close="onClose"
        @on-confirm="commit">
      <template v-slot:content>
        <el-form :model="addModel" ref="addRef" :rules="rules" label-width="85px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="菜单类型" prop="">
                <el-radio-group v-model="addModel.type">
                  <el-radio value="0" label="目录"></el-radio>
                  <el-radio value="1" label="菜单"></el-radio>
                  <el-radio value="2" label="按钮"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="上级菜单" prop="parentId">
                <el-tree-select
                    @check-change="treeClick"
                    v-model="addModel.parentId"
                    :data="treeList"
                    :render-after-expand="false"
                    show-checkbox
                    check-strictly
                    style="width: 240px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单名称:" prop="title">
                <el-input v-model="addModel.title"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="addModel.type !='2'">
            <el-col :span="12">
              <el-form-item label="菜单图标:" prop="icon">
                <!--使用图标选择器组件-->
                <ElIconPicker  v-model="addModel.icon"></ElIconPicker >
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="路由名称:" prop="name">
                <el-input v-model="addModel.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="菜单序号:" prop="orderNum">
                <el-input v-model="addModel.orderNum"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="权限字段:" prop="code">
                <el-input v-model="addModel.code"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col v-if="addModel.type !='2'" :span="12">
              <el-form-item label="路由地址:" prop="path">
                <el-input v-model="addModel.path"></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="addModel.type =='1'" :span="12">
              <el-form-item label="组件路径:" prop="url">
                <el-input v-model="addModel.url"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </SysDialog>
  </el-main>
</template>

<style scoped>

</style>
